let str = '3[abc]'
let str2 = `3[2[a]2[b]]]`
let str3 = '2[1[a]3[b]2[3[c]4[d]]]'

function toAst(str) {
  //两个指针
  let start = 0
  let end = 0

  //栈
  let stack = []

  //不断移动end指针，扫描字符串
  while (end <= (str.length - 1)) {
    //如果遇到左括号，则入栈
    if (str[end] === '[') {
      stack.push({
        //重复次数
        repeatCount: parseInt(str.substring(start, end), 10),
        //重复内容
        repeatContent: []
      })

      //更新 start指针
      start = end + 1
    } else if (str[end] === ']') {

      //保存重复内容到 栈顶节点
      if (end - start >= 1 && str[start] !== ']') {
        //有重复内容才添加
        stack[stack.length - 1].repeatContent.push(str.substring(start, end))
      }

      start = end + 1

      //如果遇到右括号，则出栈
      if (stack.length >= 2) {
        let child = stack.pop()
        //将弹出的节点 添加到父节点的重复内容数组中
        stack[stack.length - 1].repeatContent.push(child)
      } else {
        return stack[0]
      }
    }
    end++
  }
}

//console.log(toAst(str2))

function smartRepeat(ast) {
  let str = ''
  let i = 1

  while (i <= ast.repeatCount) {
    ast.repeatContent.forEach(item => {
      if (typeof item === 'string') {
        str += item
      } else if (typeof item === 'object') {
        //递归
        str += smartRepeat(item)
      }
    })
    i++
  }

  return str
}

console.log(smartRepeat(toAst(str3)))

